package cn.icanci.loopstack.bic.sdk.thread;

import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.icanci.loopstack.bic.sdk.burying.BuryingDTO;
import cn.icanci.loopstack.bic.sdk.burying.BuryingHolder;
import cn.icanci.loopstack.bic.sdk.properties.BicProperties;

/**
 * 数据上报服务
 *
 * @author icanci
 * @since 1.0 Created in 2023/08/19 12:21
 */
@Service("bicEscalationService")
public class BicEscalationServiceImpl implements BicEscalationService {
    @Resource
    private BicProperties                   bicProperties;
    private static final String             BIC_SERVER_URL_SUFFIX = "/bicApi/burying/batchSubmit";

    private static final int                CORE_SIZE             = Runtime.getRuntime().availableProcessors();

    private static final ThreadPoolExecutor ESCALATION_POOL       = new ThreadPoolExecutor(CORE_SIZE,          //
        CORE_SIZE << 1,                                                                                        //
        60L,                                                                                                   //
        TimeUnit.SECONDS,                                                                                      //
        new LinkedBlockingQueue<>(2000),                                                                       //
        runnable -> new Thread(runnable, "Escalation Biz Pool-" + runnable.hashCode()),                        //
        (r, executor) -> {
            throw new RuntimeException("Escalation Biz Pool is EXHAUSTED!");
        });

    @Override
    public void escalation(List<BuryingDTO> buryings) {
        String bicServerUrl = bicProperties.getBicServerUrl() + BIC_SERVER_URL_SUFFIX;
        ESCALATION_POOL.execute(() -> doEscalation(bicServerUrl, buryings));
    }

    private void doEscalation(String bicServerUrl, List<BuryingDTO> buryings) {
        HttpUtil.post(bicServerUrl, JSONUtil.toJsonStr(new BuryingHolder(buryings)));
    }
}
